/**
 * Created by Administrator on 2017/4/16.
 */
!(function ($) {
  /**
   * 我的商品下拉数据
   */
  var dropLoad = {
    userId: $.fn.cookie('userId'),
    isLogin: $.fn.cookie('isLogin'),
    publishType: $.fn.cookie('publish_type'),
    page: 2,
    pageSize: 10,
    totalPage: $('#totalPage').val() || 1000,
    loadHtml: $('<div class="dropload-load f15"><span class="weui-loading"></span>正在加载中...</div>'),
    noDataHtml: $('<div class="dropload-noData">没有更多数据了</div>'),
    ajaxing: false, // 判断是否加载完毕
    init: function () {
      1 == this.totalPage ? this.showNoData() : this.addScrollEvent()
    },
    showNoData: function () {
      // this.removeScrollEvent()
      $('.my_list').append(this.noDataHtml)
    },
    removeScrollEvent: function () {
      $('.weui_tab_bd').off('scroll.mylist')
    },
    addScrollEvent: function () {
      var self = this
      var scrolling = false, $window = $('.weui_tab_bd'), windowHeight = $window.height(), lastScrollTop = 0
      $window.on('scroll.mylist', function () {
        if (scrolling) return
        var nowScrollTop = $window.scrollTop()
        if ($window.scrollTop() <= lastScrollTop) {
          lastScrollTop = nowScrollTop
          return
        }
        lastScrollTop = nowScrollTop
        scrolling = true
        setTimeout(function () {
          var top
          var scrollTop = $window.scrollTop(); // 模块相对视图区域的坐标
          if ($('.my_list').is(':visible')) {
            var $module = $('.my_list')
            top = $('.my_list').position().top + 400
          }
          var heightModule = $module.height(); // 发现模块的高度
          var viewHeight = scrollTop + windowHeight
          if ((heightModule + top - viewHeight) < 50) { // 发现模块被容器隐藏的内容区域 小于50的时候
            if ($('.my_pros').is(':visible')) {
              self.getNextDataMyPro()
            }
            if ($('.my_news').is(':visible')) {
              self.getNextDataMyNews()
            }
            if ($('.my_feedback').is(':visible')) {
              self.getNextDataMyFeedBack()
            }
            if ($('.my_favs').is(':visible')) {
              self.getNextDataMyFav()
            }
          }
          // }
          scrolling = false
        }, 20)
      })
    },
    handleData: function (data) {
      var self = this
      var tpl = ''
      $.each(data, function (i, item) {
        var ahead = item.status == 1 ? '<div class="my_list_item nopass" id="' + item.id + '">' : '<div class="my_list_item" id="' + item.id + '">'
        tpl += ahead
        tpl += '<div class="img img-max"><a href="detail.html?id=' + item.id + '"><img src="' + item.images[0].smallUrl + '" data-img="' + item.images[0].smallUrl + '" alt=""></a></div>'
        tpl += '<div class="r-infos"><h4><strong>' + item.categoryName + '</strong><span class="price">￥' + item.price + '</span></h4>' +
          '<p class="weui_media_desc">' + item.desc + '</p>'
        if (item.status == 1) {
          tpl += '<span class="status_01 right">审核中</span></div>'
        }else {
          tpl += '<p class="right"><a class="btn-edit weui_btn weui_btn_mini weui_btn_default mr5">编辑</a><a class="btn-del weui_btn weui_btn_default weui_btn_mini">删除</a></p></div>'
        }
        tpl += '</div>'
      })
      if ($('.my_list').hasClass('my_pros')) {
        $('.my_pros').append(tpl)
      }
      if ($('.my_list').hasClass('my_news')) {
        $('.my_news').append(tpl)
      }
      // 判断当前页数和总页数一致，返回无数据
      if (self.totalPage == self.page) {
        self.showNoData()
      }
      // 图片懒加载
      var lazyloadImg = new LazyloadImg({
        el: '.my_list [data-img]', // 匹配元素
        top: 50, // 元素在顶部伸出长度触发加载机制
        right: 50, // 元素在右边伸出长度触发加载机制
        bottom: 50, // 元素在底部伸出长度触发加载机制
        left: 50, // 元素在左边伸出长度触发加载机制
        qriginal: false, // true，自动将图片剪切成默认图片的宽高；false显示图片真实宽高
        load: function (el) {
          el.style.cssText += '-webkit-animation: fadeIn 01s ease 0.2s 1 both;animation: fadeIn 1s ease 0.2s 1 both;'
        },
        error: function (data) {
          $.alert(data.msg)
        }
      })
    },
    handleFeedData: function (data) {
      var self = this
      var tpl = ''
      $.each(data, function (i, item) {
        var ahead = item.status == 1 ? '<div class="my_list_item nopass" feedbackid="' + item.id + '">' : '<div class="my_list_item" id="' + item.id + '">'
        tpl += ahead
        if (item.images[0]) {
          tpl += '<div class="img img-max"><img src="' + item.images[0].smallUrl + '" data-img="' + item.images[0].smallUrl + '" alt=""></div>'
        }else {
          tpl += '<div class="img img-max"><img src="imgs/default-img.png"  alt=""></div>'
        }
        tpl += '<div class="r-infos"><h4><span class="date">' + formatDateTime(item.createdTime) + '</span></h4>' +
          '<p class="weui_media_desc">' + item.message + '</p>'
        if (item.status == 1) {
          tpl += '<span class="status_01 right">审核中</span></div>'
        }else {
          tpl += '<p class="right"><a class="btn-feedback-del weui_btn weui_btn_default weui_btn_mini">删除</a></p></div>'
        }
        tpl += '</div>'
      })
      if ($('.my_list').hasClass('my_feedback')) {
        $('.my_feedback').append(tpl)
      }
      // 判断当前页数和总页数一致，返回无数据
      if (self.totalPage == self.page) {
        self.showNoData()
      }
      // 图片懒加载
      var lazyloadImg = new LazyloadImg({
        el: '.my_list [data-img]', // 匹配元素
        top: 50, // 元素在顶部伸出长度触发加载机制
        right: 50, // 元素在右边伸出长度触发加载机制
        bottom: 50, // 元素在底部伸出长度触发加载机制
        left: 50, // 元素在左边伸出长度触发加载机制
        qriginal: false, // true，自动将图片剪切成默认图片的宽高；false显示图片真实宽高
        load: function (el) {
          el.style.cssText += '-webkit-animation: fadeIn 01s ease 0.2s 1 both;animation: fadeIn 1s ease 0.2s 1 both;'
        },
        error: function (data) {
          $.alert(data.msg)
        }
      })
    },
    handleFavData: function (data) {
      var self = this
      var tpl = ''
      $.each(data, function (i, item) {
        var imgs = item.images
        tpl += '<div class="fav-item" categoryid="' + item.id + '"><div class="fav-head"><div class="title">' + item.categoryName + '</div>' +
          '<span class="fr">￥' + item.price + '</span></div><div class="swiper-container"><div class="swiper-wrapper">'
        for (var j = 0;j < imgs.length;j++) {
          tpl += '<div class="swiper-slide"><a href=detail.html?id=' + item.id + '><img data-img="' + imgs[j].smallUrl + '" src="' + imgs[j].smallUrl + '" /></a></div>'
        }
        tpl += '</div></div><div class="des-info">' + item.desc + '</div>' +
          '<p class="right"><a class="btn-fav-del weui_btn weui_btn_default weui_btn_mini">删除</a>' +
          '</p></div>'
      })
      if ($('.my_list').hasClass('my_favs')) {
        $('.my_favs').append(tpl)
        // slider
        new Swiper('.my_favs .swiper-container', {
          slidesPerView: 3,
          spaceBetween: 10
        })
      }
      // 判断当前页数和总页数一致，返回无数据
      if (self.totalPage == self.page) {
        self.showNoData()
      }
      // 图片懒加载
      var lazyloadImg = new LazyloadImg({
        el: '.my_list [data-img]', // 匹配元素
        top: 50, // 元素在顶部伸出长度触发加载机制
        right: 50, // 元素在右边伸出长度触发加载机制
        bottom: 50, // 元素在底部伸出长度触发加载机制
        left: 50, // 元素在左边伸出长度触发加载机制
        qriginal: false, // true，自动将图片剪切成默认图片的宽高；false显示图片真实宽高
        load: function (el) {
          el.style.cssText += '-webkit-animation: fadeIn 01s ease 0.2s 1 both;animation: fadeIn 1s ease 0.2s 1 both;'
        },
        error: function (data) {
          $.alert(data.msg)
        }
      })
    },
    getNextDataMyPro: function () {
      var self = this
      if (self.ajaxing == true) return
      if (self.totalPage > self.page) {
        if ($('.my_list')) {
          self.loadHtml.appendTo('.my_list')
        }
        self.ajaxing = true
        $.ajax({
          url: API_URL + USER_PRODUCTS_URL + '?page=' + self.page + '&pageSize=' + self.pageSize,
          type: 'post',
          dataType: 'jsonp',
          data: {userId: self.userId,type: 1},
          success: function (data) {
            self.ajaxing = false
            self.loadHtml.remove()
            var datas = data.result
            if (datas && datas.length > 0) {
              self.page = self.page + 1
              self.handleData(datas)
              if (datas.length < self.pageSize) {
                self.totalPage = self.page
                self.showNoData()
              }
            }else {
              self.totalPage = self.page
              self.showNoData()
            }
          },
          error: function () {
            self.ajaxing = false
            self.loadHtml.remove()
          }
        })
      }
    },
    getNextDataMyNews: function () {
      var self = this
      var self = this
      if (self.ajaxing == true) return
      if (self.totalPage > self.page) {
        if ($('.my_list')) {
          self.loadHtml.appendTo('.my_list')
        }
        self.ajaxing = true
        $.ajax({
          url: API_URL + USER_PRODUCTS_URL + '?page=' + self.page + '&pageSize=' + self.pageSize,
          type: 'post',
          dataType: 'jsonp',
          data: {userId: self.userId,type: 2},
          success: function (data) {
            self.ajaxing = false
            self.loadHtml.remove()
            var datas = data.result
            if (datas && datas.length > 0) {
              self.page = self.page + 1
              self.handleData(datas)
              if (datas.length < self.pageSize) {
                self.totalPage = self.page
                self.showNoData()
              }
            }else {
              self.totalPage = self.page
              self.showNoData()
            }
          },
          error: function () {
            self.ajaxing = false
            self.loadHtml.remove()
          }
        })
      }
    },
    getNextDataMyFeedBack: function () {
      var self = this
      if (self.ajaxing == true) return
      if (self.totalPage > self.page) {
        if ($('.my_list')) {
          self.loadHtml.appendTo('.my_list')
        }
        self.ajaxing = true
        $.ajax({
          url: API_URL + FEEDBACKS_URL + '?page=' + self.page + '&pageSize=' + self.pageSize,
          type: 'post',
          dataType: 'jsonp',
          data: {userId: self.userId},
          success: function (data) {
            self.ajaxing = false
            self.loadHtml.remove()
            var datas = data.result
            if (datas && datas.length > 0) {
              self.page = self.page + 1
              self.handleFeedData(datas)
              if (datas.length < self.pageSize) {
                self.totalPage = self.page
                self.showNoData()
              }
            }else {
              self.totalPage = self.page
              self.showNoData()
            }
          },
          error: function () {
            self.ajaxing = false
            self.loadHtml.remove()
          }
        })
      }
    },
    getNextDataMyFav: function () {
      var self = this
      if (self.ajaxing == true) return
      if (self.totalPage > self.page) {
        if ($('.my_list')) {
          self.loadHtml.appendTo('.my_list')
        }
        self.ajaxing = true
        $.ajax({
          url: API_URL + FAVORITES_URL + '?page=' + self.page + '&pageSize=' + self.pageSize,
          type: 'post',
          dataType: 'jsonp',
          data: {userId: self.userId,type: 1},
          success: function (data) {
            self.ajaxing = false
            self.loadHtml.remove()
            var datas = data.result
            if (datas && datas.length > 0) {
              self.page = self.page + 1
              self.handleFavData(datas)
              if (datas.length < self.pageSize) {
                self.totalPage = self.page
                self.showNoData()
              }
            }else {
              self.totalPage = self.page
              self.showNoData()
            }
          },
          error: function () {
            self.ajaxing = false
            self.loadHtml.remove()
          }
        })
      }
    }
  }
  var my = {
    userId: $.fn.cookie('userId'),
    isLogin: $.fn.cookie('isLogin'),
    init: function () {
      this.getUserInfo()
      this.defaultLoad(1)
      this.delRun()
      this.checkTips()
      this.saveUrl()
      this.delPros()
      this.delNews()
      this.delFeedbacks()
      dropLoad.init()
      loadNav()
    },

    saveUrl: function () {
      $.fn.cookie('curUrl', window.location.href)
    },
    // dropLoad:function(){
    //  var self = this
    //  var $window = $('.weui_tab_bd')
    //  $window.on('scroll',function(){
    //      setTimeout(function(){
    //          var $windowHeight = $window.height()
    //          var scrolling = false
    //          var $module = $('.my_list')
    //          var eleHeight = $module.height()
    //          var winTop = $window.scrollTop()
    //          var eleTop = $module.position().top+450
    //          var viewH = winTop+ $windowHeight
    //          if ((eleHeight+eleTop-viewH)<50) {
    //                if($('.my_list').hasClass('my_pros')){
    //                    self.getPros()
    //                }
    //          }
    //      },30)
    //  })
    // },

    /**
     * /默认获取商品
     * @param type =1
     */
    defaultLoad: function (type) {
      var self = this
      setTimeout(function () {
        var publishType = $.fn.cookie('publish_type')
        if (publishType == 1) {
          $('.my-tab .item').eq(0).addClass('on').siblings().removeClass('on')
        }
        if (publishType == 2) {
          $('.my-tab .item').eq(1).addClass('on').siblings().removeClass('on')
          self.getNewsInfo()
        }
        if (publishType == 3) {
          $('.my-tab .item').eq(2).addClass('on').siblings().removeClass('on')
          self.getFeedback()
        }
      }, 1000)
      if (self.isLogin) {
        $.ajax({
          url: API_URL + USER_PRODUCTS_URL,
          type: 'get',
          dataType: 'jsonp',
          data: {userId: self.userId,type: type,page: 1,pageSize: 10},
          success: function (data) {
            if (data.ok == true) {
              var tpl = template('my_list_tpl', data)
              $('.weui_tab_bd').empty().html(tpl)
              $('#totalPage').val(data.page.totalPage)
              dropLoad.page = 2
            }
          },
          error: function (data) {
            $.toptips(data.msg)
          }
        })
      }else {
        $.toptips('请登录绑定后再尝试!')
      }
    },
    /**
     * 获取用户信息
     * @id=1
     */
    getUserInfo: function () {
      var self = this
      $.ajax({
        url: API_URL + GET_USER_INFO,
        type: 'post',
        dataType: 'jsonp',
        data: {id: self.userId},
        success: function (data) {
          var datas = data.result
          if (data.ok == true) {
            var tpl = template('user_head_tpl', datas)
            $('.my-header').empty().html(tpl)
            
            if (datas.status == -1) {
              $.modal({
                title: '您的账号已被停用！',
                buttons: [
                  { text: '知道了', onClick: function () {
                      window.location.href = 'index.html'
                  } },
                  { text: '申诉', className: 'default',onClick: function () {
                      window.location.href = 'appeals.html'
                  }}
                ]
              })
            }
            if (datas.status == 0) {
              $.modal({
                title: '您的账号已被冻结！！',
                buttons: [
                  { text: '知道了', onClick: function () {
                      window.location.href = 'index.html'
                  } },
                  { text: '申诉', className: 'default',onClick: function () {
                      window.location.href = 'appeals.html'
                  }}
                ]
              })
            }
          }
          // 事件绑定切换栏目
          $('.my-tab .item').on('click', function () {
            $(this).addClass('on').siblings().removeClass('on')
            var type = $(this).data('type')
            console.log($('#totalPage').val())
            if (type == 1) {
              self.defaultLoad(type)
              $.fn.cookie('publish_type', 1)
            }
            if (type == 2) {
              self.getNewsInfo()
              $.fn.cookie('publish_type', 2)
            }
            if (type == 3) {
              self.getFeedback()
              $.fn.cookie('publish_type', 3)
            }
            if (type == 4) {
              self.getFavorites()
              $.fn.cookie('publish_type', 4)
            }
          })
          // 编辑
          $('.weui_tab_bd').delegate('.btn-pros-edit', 'click', function () {
            var id = $(this).closest('div.my_list_item').attr('myprosid')
            window.location.href = 'update.html?id=' + id
          })
          $('.weui_tab_bd').delegate('.btn-news-edit', 'click', function () {
            var id = $(this).closest('div.my_list_item').attr('newsid')
            window.location.href = 'update.html?id=' + id
          })
        },
        error: function (data) {
          $.toptips(data.msg)
        }
      })
    },
    // 审核中
    checkTips: function () {
      $('.weui_tab_bd').delegate('.nopass', 'click', function () {
        $.alert('我们会尽快审核，谢谢您的配合!', '')
      })
    },
    delPros: function () {
      var self = this
      $('.weui_tab_bd').delegate('.btn-pros-del', 'click', function () {
        var that = $(this)
        var idv = that.closest('.my_list_item').attr('myprosid')
        $.confirm('删除后无法恢复,', '是否确认删除?', function () {
          $.ajax({
            url: API_URL + DELETE_PRODUCT_URL,
            type: 'post',
            dataType: 'jsonp',
            data: {userId: self.userId,id: idv},
            success: function (data) {
              if (data.ok == true) {
                $.toast('删除成功!')
                that.closest('.my_list_item').remove()
              }
            },
            error: function (data) {
              $.toptips(data.msg)
            }
          })
        }, function () {
          return
        })
      })
    },
    delNews: function () {
      var self = this
      $('.weui_tab_bd').delegate('.btn-news-del', 'click', function () {
        var that = $(this)
        var idv = that.closest('.my_list_item').attr('newsid')
        $.confirm('删除后无法恢复,', '是否确认删除?', function () {
          $.ajax({
            url: API_URL + DELETE_PRODUCT_URL,
            type: 'post',
            dataType: 'jsonp',
            data: {userId: self.userId,id: idv},
            success: function (data) {
              if (data.ok == true) {
                $.toast('删除成功!')
                that.closest('.my_list_item').remove()
              }
            },
            error: function (data) {
              $.toptips(data.msg)
            }
          })
        }, function () {
          return
        })
      })
    },
    // 删除反馈
    delFeedbacks: function () {
      var self = this
      $('.weui_tab_bd').delegate('.btn-feedback-del', 'click', function () {
        var that = $(this)
        var idv = that.closest('.my_list_item').attr('feedbackid')
        $.confirm('删除后无法恢复,', '是否确认删除?', function () {
          $.ajax({
            url: API_URL + DELETE_FEEDBACK_URL,
            type: 'post',
            dataType: 'jsonp',
            data: {userId: self.userId,id: idv},
            success: function (data) {
              if (data.ok == true) {
                $.toast('删除成功!')
                that.closest('.my_list_item').remove()
              }
            },
            error: function (data) {
              $.toptips(data.msg)
            }
          })
        }, function () {
          return
        })
      })
    },
    /**
     * 删除收藏
     */
    delRun: function () {
      var self = this
      $('.weui_tab_bd').delegate('.btn-fav-del', 'click', function () {
        var that = $(this)
        var idv = that.closest('.fav-item').attr('categoryid')
        $.confirm('删除后无法恢复,', '是否确认删除?', function () {
          $.ajax({
            url: API_URL + DEL_FAVORITE_URL,
            type: 'post',
            dataType: 'jsonp',
            data: {userId: self.userId,id: idv},
            success: function (data) {
              if (data.ok == true) {
                $.toast('删除成功!')
                that.closest('.fav-item').remove()
              }
            },
            error: function (data) {
              $.toptips(data.msg)
            }
          })
        }, function () {
          return
        })
      })
    },
    /*
    * 获取资讯
    * @type=2
     */
    getNewsInfo: function () {
      var self = this
      $.ajax({
        url: API_URL + USER_PRODUCTS_URL,
        type: 'get',
        dataType: 'jsonp',
        data: {userId: self.userId,type: 2,page: 1,pageSize: 10},
        success: function (data) {
          if (data.ok == true) {
            var tpl = template('my_news_tpl', data)
            $('.weui_tab_bd').empty().html(tpl)
            $('#totalPage').val(data.page.totalPage)
            dropLoad.page = 2
            $('.my_news').delegate('.btn-del', 'click', function () {
              var that = $(this)
              var id = that.closest('.my_list_item').attr('newsid')
              $.confirm('删除后无法恢复,', '是否确认删除?', function () {
                self.delProducts(id)
                that.closest('.my_list_item').remove()
              }, function () {
                return
              })
            })
          }
        },
        error: function (data) {
          $.toptips(data.msg)
        }
      })
    },
    /**
     * 获取收藏商品
     * @type=2
     */
    getFavorites: function () {
      var self = this
      $.ajax({
        url: API_URL + FAVORITES_URL,
        type: 'get',
        dataType: 'jsonp',
        data: {userId: self.userId,type: 0,page: 1,pageSize: 10},
        success: function (data) {
          if (data.ok == true) {
            $('#totalPage').val(data.page.totalPage)
            dropLoad.page = 2
            var tpl = template('my_fav_tpl', data)
            $('.weui_tab_bd').empty().html(tpl)
            new Swiper('.swiper-container', {
              slidesPerView: 3,
              spaceBetween: 10
            })
          }
        },
        error: function (data) {
          $.toptips(data.msg)
        }
      })
    },
    /**
     * 获取反馈
     * @userId
     */
    getFeedback: function () {
      var self = this
      $.ajax({
        url: API_URL + FEEDBACKS_URL,
        type: 'post',
        dataType: 'jsonp',
        data: {userId: self.userId,page: 1,pageSize: 10},
        success: function (data) {
          if (data.ok == true) {
            $('#totalPage').val(data.page.totalPage)
            dropLoad.page = 2
            var tpl = template('my_feedback_tpl', data)
            $('.weui_tab_bd').empty().html(tpl)
          }else {
            $.alert(data.msg)
          }
        },
        error: function (data) {
          $.alert(data.msg)
        }
      })
    }

  }
  $(function () {
    my.init()
  })
})(Zepto)
